import { Articles, Channel } from '@/types/data'
import { HomeAction } from '@/types/store'
import sortBy from 'lodash/sortBy'
type HomeState = {
  channels: Channel[]
  restChannels: Channel[]
  channelActiveKey: number
  channelActicles: {
    [key in number]?: Articles
  }
}
const initialState: HomeState = {
  channels: [],
  restChannels: [],
  channelActiveKey: 0,
  channelActicles: {},
}
export const home = (state = initialState, action: HomeAction): HomeState => {
  switch (action.type) {
    //获取频道数据
    case 'home/getChannels':
      return { ...state, channels: action.payload }
    case 'home/getAllChannels':
      return { ...state, restChannels: action.payload }
    case 'home/changeTab':
      return { ...state, channelActiveKey: action.payload }
    //删除
    case 'home/delChannel':
      // console.log(action.payload)

      return {
        ...state,
        channels: state.channels.filter(
          (item) => item.id !== action.payload.id
        ),

        // 可选频道
        restChannels: sortBy([...state.restChannels, action.payload], ['id']),
      }
    //添加
    case 'home/addChannel':
      return {
        ...state,
        channels: [...state.channels, action.payload],
        restChannels: state.restChannels.filter(
          (item) => item.id !== action.payload.id
        ),
      }
    case 'home/getChannelArticle':
      // const curChannelArticle=state.channelActicles[action.payload.channelId]??{pre_timestamp:null,results:[]}

      const {
        channelId,
        article: { pre_timestamp, results },
      } = action.payload
      const currentResults = state.channelActicles[channelId]?.results ?? []
      return {
        ...state,
        channelActicles: {
          ...state.channelActicles,
          [channelId]: {
            pre_timestamp,
            results: [...currentResults, ...results],
          },
        },
      }
    case 'home/getNewestChannelArticle':
      const {
        channelI,
        articl: { pre_timestamp: id, results: date },
      } = action.payload
      const currentResult = state.channelActicles[channelI]?.results ?? []
      return {
        ...state,
        channelActicles: {
          ...state.channelActicles,
          [channelI]: {
            pre_timestamp: id,
            results: [...date, ...currentResult],
          },
        },
      }
    default:
      return state
  }
}
